package controller

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"context"
	"fmt"
	"net/url"
	"io"
	"os"
	"time"
	"gowork/memberGoKit/client/transport"
	memEndpoint "gowork/memberGoKit/client/endpoint"
	httpTransport "github.com/go-kit/kit/transport/http"
	"gowork/memberGoKit/client/util"
	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/sd"
	"github.com/go-kit/kit/sd/lb"
	"github.com/go-kit/kit/log"
)

type MemberKitController struct{
    Ctx  iris.Context
}

var logger log.Logger = log.NewLogfmtLogger(os.Stdout)

func (c *MemberKitController) PostKitinsert() mvc.Result {
	memberList := c.Ctx.FormValue("memberList")
	
	factory := func(serviceUrl string)(endpoint.Endpoint, io.Closer, error){
		tart, _ := url.Parse("http://" + serviceUrl)
		fmt.Println(serviceUrl)
		fmt.Println("tart:", tart)
		return httpTransport.NewClient("GET", tart, transport.MemberInsertRequest, transport.MemberMapResponse).Endpoint(), nil, nil
	}

	endpointer:= sd.NewEndpointer(util.Instancer, factory, logger)

	endpoints, eErr := endpointer.Endpoints()
	if eErr != nil{
		fmt.Println(eErr)
		return mvc.Response{
			Object : eErr,
		}
	}
	fmt.Println("服务端实例:", endpoints, len(endpoints))


	//负载均衡
	//myLb := lb.NewRoundRobin(endpointer)
	myLb := lb.NewRandom(endpointer, time.Now().UnixNano())
	
	memberInsertFunc, uErr := myLb.Endpoint()
	if uErr != nil{
		fmt.Println("获取方法报错", uErr)
		return mvc.Response{
			Object : uErr,
		}
	}
	ctx := context.Background()
	res, err := memberInsertFunc(ctx, memEndpoint.MemberRequestOrResponse{MemberList : memberList,})
	if err != nil{
		fmt.Println("调用方法报错", err)
		return mvc.Response{
			Object : err,
		}
	}

	return mvc.Response{
        Object : res.(memEndpoint.MemberMapResponse),
    }
}

func (c *MemberKitController) PostKitquery() mvc.Result {
	
	factory := func(serviceUrl string)(endpoint.Endpoint, io.Closer, error){
		tart, _ := url.Parse("http://" + serviceUrl)
		return httpTransport.NewClient("GET", tart, transport.MemberQueryRequest, transport.MemberQueryResponse).Endpoint(), nil, nil
	}

	endpointer:= sd.NewEndpointer(util.Instancer, factory, logger)

	//负载均衡
	myLb := lb.NewRoundRobin(endpointer)
	//myLb := lb.NewRandom(endpointer, time.Now().UnixNano())
	
	memberQueryFunc, uErr := myLb.Endpoint()
	if uErr != nil{
		fmt.Println(uErr)
		return mvc.Response{
			Object : uErr,
		}
	}
	ctx := context.Background()
	res, err := memberQueryFunc(ctx, memEndpoint.MemberNilRequest{})
	if err != nil{
		fmt.Println(err)
		return mvc.Response{
			Object : err,
		}
	}
	
	return mvc.Response{
        Object : res.(memEndpoint.MemberRequestOrResponse),
    }
}